from django.shortcuts import render
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from .Query.QueryFactory import QueryFactory


# Create your views here.
class StudentGrades:
    """
    学生信息查询接口类
    """
    # 学生成绩查询结果展示页面HTML页面路径
    __studentGrades_html = "studentGrades/studentGrades.html"
    __statistics_html = "studentGrades/query_fail_by_major.html"
    __count_no_pass_in_major = "studentGrades/count_no_pass_in_major.html"

    # 学生成绩查询结果展示页面
    def students_grades_views(self, request):
        return render(request, self.__studentGrades_html, {"student_grades": "active"})

    # 专业成绩统计分析页面
    def statistics_views(self, request):
        return render(request, self.__statistics_html, {"statistics": "active"})

    # 专业不及格人数页面

    def count_no_pass_in_major(self, request):
        return render(request, self.__count_no_pass_in_major, {"no_pass": "active"})

    @method_decorator(require_http_methods(["POST"]))
    def query_student_grade(self, request):
        """
        查询学生成绩接口
        """
        req = request.POST
        query_method = req.get("query_method", "help")
        # 获取指定方法类并且实例化
        try:
            # 获取调用的方法类并实例化
            method = QueryFactory.get_query_method(query_method)(req)
            # 查询结果
            result = method.get_result()
            # 结果表头
            description = method.get_description()
            # 数据集长度
            length = method.get_length()
            # 做成 [ {description:result} ] 的json格式
            # rows = [dict(zip(description, row)) for row in result]
            data = {
                "description": description,
                "result": result
            }
            return JsonResponse(data, safe=False)
        except ValueError as te:
            print(self.__class__, te)
            return JsonResponse({"ValueError": str(te)}, safe=False)


student_grades_views = StudentGrades()
